package cn.blunce.utils.XmlParse;

import android.util.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class SAXParsePersonHelper extends DefaultHandler {

    private static final String TAG = "SAXForHandler";
    private List<Person> persons;

    /**
     * ��¼ǰһ����ǩ������
     */
    private String perTag;

    /**
     * ��¼��ǰPerson
     */
    private Person person;

    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        persons = new ArrayList<Person>();
        Log.i(TAG, "***startDocument()***");
    }

    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        if ("person".equals(localName)) {
            for (int i = 0; i < attributes.getLength(); i++) {
                Log.i(TAG, "attributeName:" + attributes.getLocalName(i)
                        + "  attributeValue:" + attributes.getValue(i));
                person = new Person();
                person.setId(Integer.valueOf(attributes.getValue(i)));
            }
        }
        perTag = localName;
        Log.i(TAG, "***startElement()****");
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        String data = new String(ch, start, length).trim();
        if (!"".equals(data)) {
            Log.i(TAG, "content:" + data);
            if ("name".equals(perTag)) {
                person.setName(data);
            } else if ("age".equals(perTag)) {
                person.setAge(new Short(data));
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        Log.i(TAG, qName + "***endElement()***");
        if ("person".equals(localName)) {
            persons.add(person);
            person = null;
        }
        perTag = null;
    }

    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        Log.i(TAG, "***endDocument()***");
    }

    public List<Person> getPersons() {
        return persons;
    }

}